#include "employee.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>

Employee::Employee(QObject *parent) : ORMObject(parent)
{
    setTableName("employees");
}

Employee::~Employee()
{
    // 清理所有地址对象
    qDeleteAll(m_addresses);
}

QString Employee::name() const
{
    return property("name").toString();
}

void Employee::setName(const QString &name)
{
    setProperty("name", name);
}

int Employee::age() const
{
    return property("age").toInt();
}

void Employee::setAge(int age)
{
    setProperty("age", age);
}

QSet<Address*> Employee::addresses() const
{
    return m_addresses;
}

void Employee::setAddresses(const QSet<Address*> &addresses)
{
    // 清理现有地址
    qDeleteAll(m_addresses);
    m_addresses.clear();
    
    // 添加新地址
    foreach (Address* addr, addresses) {
        if (addr) {
            addr->setParent(this);
            m_addresses.insert(addr);
        }
    }
}

void Employee::addAddress(Address* address)
{
    if (address) {
        address->setParent(this);
        address->setProperty("employee_id", id());
        m_addresses.insert(address);
    }
}

void Employee::saveChildren()
{
    // 保存所有地址
    saveCollectionProperty<Address*>("addresses", "employee_id");
}

void Employee::loadChildren()
{
    // 加载所有地址
    loadCollectionProperty<Address*>("addresses", "employee_id");
    
    // 更新内存中的集合
    QVariant addressesVariant = property("addresses");
    if (addressesVariant.canConvert<QList<QObject*>>()) {
        QList<QObject*> addressList = addressesVariant.value<QList<QObject*>>();
        m_addresses.clear();
        
        foreach (QObject* obj, addressList) {
            Address* addr = qobject_cast<Address*>(obj);
            if (addr) {
                m_addresses.insert(addr);
            }
        }
    }
}    